package com.snap.vseries.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.snap.vseries.R;
import com.snap.vseries.adapter.SearchHistoryAdapter;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.utils.SpUtils;
import com.snap.vseries.utils.ToastUtils;
import com.snap.vseries.utils.TopTitleUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

import static com.snap.vseries.utils.SpUtils.CONTENT_LIST;

/**
 * @author Rachel
 */
public class HisSearchActivity extends BaseActivity {
    private final static int RESULT_LIMIT_COUNT = 6;
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.search_bt)
    ImageView searchBt;
    @BindView(R.id.device_rv)
    RecyclerView recyclerView;
    private List<String> contentList;

    @Override
    protected int layoutResId() {
        return R.layout.activity_search_his;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    private void initData() {
        contentList = SpUtils.get().getDataList(CONTENT_LIST, String.class);
        if (contentList == null) {
            contentList = new ArrayList<>();
            SpUtils.get().setDataList(CONTENT_LIST, contentList);
        }
    }

    private static String getSpecialCharFilter() {
        String regex = "^[0-9|a-zA-Z|.|_|\\-|\u4e00-\u9fa5]+$";

        return regex;
    }

    private void initView() {
        new TopTitleUtils(this).setTitle(R.string.search_exp);
        showSoftInputFromWindow(searchEt);
        searchBt.setOnClickListener(v -> {
            if (TextUtils.isEmpty(searchEt.getText())) {
                ToastUtils.get().showText("搜索内容不允许为空");
                return;
            }
            String content = searchEt.getText().toString().trim();
            saveSearchContent(content);
            Intent intent = new Intent(HisSearchActivity.this, HisSearchResultActivity.class);
            intent.putExtra("search_content", content);
            startActivity(intent);
            finish();
        });
        //=======================测试数据=============================
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(new SearchHistoryAdapter(this, contentList));
        searchEt.setSelection(searchEt.getText().length());
        InputFilter typeFilter = (source, start, end, dest, dstart, dend) -> {
            Pattern p = Pattern.compile(getSpecialCharFilter());
            Matcher m = p.matcher(source.toString());
            if (!m.matches()) {
                return "";
            }
            return null;
        };
        searchEt.setFilters(new InputFilter[]{typeFilter});
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {
                    int count = 0;
                    int index = 0;
                    int startIndex = 0;
                    while (index < s.length()) {
                        char c = s.charAt(index);
                        if (c < 128) {
                            //英文、数字等
                            count = count + 1;
                        } else {
                            //汉字等
                            count = count + 2;
                        }
                        if (count > 20) {
                            startIndex = index;
                            break;
                        }
                        index++;
                    }
                    if (startIndex != 0) {
                        ToastUtils.get().showText("超出指定长度");
                        //删除部分字符串 为[x,y) 包含x位置不包含y
                        s.delete(startIndex, s.length());
                    }
                }
            }
        });
    }
    private void saveSearchContent(String content) {
        Iterator<String> it = contentList.iterator();
        while (it.hasNext()) {
            String c = it.next();
            if (c.equals(content)) {
                it.remove();
                break;
            }
        }
        contentList.add(0, content);
        while (RESULT_LIMIT_COUNT < contentList.size()) {
            contentList.remove(contentList.size() - 1);
        }
        SpUtils.get().setDataList(CONTENT_LIST, contentList);
    }

    public void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}
